<template>
  <div class="">
    <a-modal
      v-model:visible="visible"
      :title="dialogTitle"
      :ok-loading="btnLoading"
      :modal-style="modalStyle"
      :body-style="bodyStyle"
      :mask-closable="false"
      @cancel="dialogCancel"
      @before-ok="dialogBeforeOk"
    >
      <a-form ref="formRef" :model="formModel">
        <a-form-item field="parent_id" label="上一级" label-col-flex="120px">
          <a-tree-select
            v-model="formModel.parent_id"
            :data="treeDatas"
            :field-names="{ key: 'id', title: 'name', icon: '' }"
            placeholder="一级菜单"
            allow-search
            allow-clear
          />
        </a-form-item>
        <a-form-item field="is_child" label="是否复制子集" label-col-flex="120px">
          <a-radio-group v-model="formModel.is_child">
            <a-radio :value="1">是</a-radio>
            <a-radio :value="0">否</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
  import { ref } from 'vue';

  import useVisible from '@/hooks/visible';
  import { apiCopy } from '@/api/admin-menu';

  const props = defineProps({
    visible: {
      type: Boolean,
      default: false,
    },
    title: {
      type: String,
      default: '',
    },
    id: {
      type: [Number, String],
      default: '',
    },
    treeDatas: {
      type: Array,
      default() {
        return [];
      },
    },
  });
  const emit = defineEmits(['saveCallback']);

  const baseFormModel = () => {
    return {
      id: '',
      parent_id: '',
      is_child: 1,
    };
  };
  const formRef = ref();
  const formModel = ref(baseFormModel());
  const modalStyle = {
    width: '460px',
    height: '260px',
  };
  const bodyStyle = {
    height: 'calc(100% - 108px)',
    overflow: 'auto',
  };

  const { visible, setVisible } = useVisible(false);
  const dialogTitle = ref();
  const btnLoading = ref(false);

  // 表单重置
  const reset = async () => {
    formModel.value = baseFormModel();
    await formRef.value?.resetFields();
  };
  const fetchData = async (row) => {
    setVisible(true);
    dialogTitle.value = '复制';

    formModel.value.id = row.id;
  };
  // 提交
  const submit = async (done) => {
    try {
      const ruleRes = await formRef.value?.validate();
      if (!ruleRes) {
        await apiCopy(formModel.value);
        done();
        emit('saveCallback');
      } else {
        done(false);
      }
    } catch (err) {
      done(false);
    } finally {
      done(false);
    }
  };

  const dialogCancel = () => {
    setVisible(false);
    reset();
  };
  const dialogBeforeOk = (done) => {
    submit(done);
  };

  // 暴露方法【给父级调用】
  defineExpose({
    fetchData,
  });
</script>

<style scoped lang="less">

</style>
